
//#include "pt.h"
//#include "ptdef.h"
//#include "ptdebug.h"
#include "pt-thread.h"
#include "completion.h"


#define PT_COMPLETED    1
#define PT_UNCOMPLETED  0

void pt_completion_init(struct pt_completion *completion)
{

    PT_ASSERT(completion != PT_NULL);

    pt_hw_interrupt_disable();
    completion->flag = PT_UNCOMPLETED;
    pt_list_init(&completion->suspended_list);
    pt_hw_interrupt_enable();

}

int32_t pt_completion_wait(struct pt_completion *completion)
{
    PT_ASSERT(completion != PT_NULL);

    pt_hw_interrupt_disable();

    if (completion->flag != PT_COMPLETED){
        return -PT_ETIMEOUT;
    }

    completion->flag = PT_UNCOMPLETED;
    pt_hw_interrupt_enable();

    return PT_EOK;
}


void pt_completion_done(struct pt_completion *completion)
{
    PT_ASSERT(completion != PT_NULL);
    PT_ASSERT(completion->suspended_list.next != PT_NULL);
    PT_ASSERT(completion->suspended_list.prev != PT_NULL);

    if ( PT_COMPLETED == completion->flag ){
        return;
    }

    pt_hw_interrupt_disable();
    completion->flag = PT_COMPLETED;

    /* resume suspended thread */
    if (!pt_list_isempty( &(completion->suspended_list) ) ){

        pt_ipc_list_resume( &(completion->suspended_list) );

        /* enable interrupt */
        pt_hw_interrupt_enable();

        return;
    }
    pt_hw_interrupt_enable();
}


